import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { GetUserLoginInfo } from '@/service/user'

const routes = [
  {
    path: '/',
    redirect: '/home'
  }, {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login')
  }, {
    path: '/home',
    component: () => import('@/views/Home'),
    children: [{
      path: '',
      component: () => import('@/views/homepage/Homepage')
    }, {
      path: '/u/:domain',
      name: 'u',
      component: () => import('@/views/user/Domain'),
      children: [{
        path: '',
        component: () => import('@/views/user/domain/UserPage')
      }, {
        path: 'followers',
        name: 'followers',
        component: () => import('@/views/user/domain/Follower')
      }, {
        path: 'following',
        name: 'following',
        component: () => import('@/views/user/domain/Following')
      }]
    }, {
      path: '/blog/:id',
      component: () => import('@/views/blog/Blog')
    }, {
      path: '/search',
      name: 'search',
      component: () => import('@/views/search/Search')
    }, {
      path: '/message',
      component: () => import('@/views/user/Message'),
      meta: {
        isLogin: true
      }
    }, {
      path: '/settings',
      component: () => import('@/views/user/Settings'),
      meta: {
        isLogin: true
      }
    }]
  }, {
    path: '/blog/edit',
    component: () => import('@/views/blog/BlogEdit'),
    meta: {
      isLogin: true
    }
  }, {
    path: '/manage',
    name: 'manage',
    redirect: '/manage/console',
    component: () => import('@/views/Manage'),
    meta: {
      breadcrumbName: '管理端',
      isAuth: true
    },
    children: [
      {
        path: '/manage/console',
        name: 'manage/console',
        component: () => import('@/views/manage/ManageConsole'),
        meta: {
          breadcrumbName: '控制台',
          isAuth: true
        }
      },
      {
        path: '/manage/blog',
        name: 'creator/blog',
        component: () => import('@/views/manage/BlogManage'),
        meta: {
          breadcrumbName: '博客管理',
          isAuth: true
        }
      },
      {
        path: '/manage/classification',
        name: 'creator/classification',
        component: () => import('@/views/manage/ClassificationManage'),
        meta: {
          breadcrumbName: '分类管理',
          isAuth: true
        }
      },
      {
        path: '/manage/tag',
        name: 'creator/tag',
        component: () => import('@/views/manage/TagManage'),
        meta: {
          breadcrumbName: '标签管理',
          isAuth: true
        }
      },
      {
        path: '/manage/comment',
        name: 'creator/comment',
        component: () => import('@/views/manage/CommentManage'),
        meta: {
          breadcrumbName: '评论管理',
          isAuth: true
        }
      },
      {
        path: '/manage/user',
        name: 'auth/user',
        component: () => import('@/views/manage/UserManage'),
        meta: {
          breadcrumbName: '用户管理',
          isAuth: true
        }
      },
      {
        path: '/manage/role',
        name: 'auth/role',
        component: () => import('@/views/manage/RoleManage'),
        meta: {
          breadcrumbName: '角色管理',
          isAuth: true
        }
      },
      {
        path: '/manage/resources',
        name: 'auth/resources',
        component: () => import('@/views/manage/ResourcesManage'),
        meta: {
          breadcrumbName: '资源管理',
          isAuth: true
        }
      },
      {
        path: '/manage/alert',
        name: 'alert',
        component: () => import('@/views/manage/AlertManage'),
        meta: {
          breadcrumbName: '举报处理',
          isAuth: true
        }
      }
    ]
  }, {
    path: '/error/:code',
    name: 'error',
    component: () => import('@/views/Error')
  }, {
    // 未匹配上的路径跳转404页面
    path: '/:catchAll(.*)',
    redirect: '/error/404'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  // 登录页和异常页直接放行
  if (to.name === 'login' || to.name === 'error') {
    next()
    return
  }
  // 如果localStorage中存在用户信息，但是vuex中无用户信息，说明页面刷新
  if (store.getters.user.id.trim().length === 0 && localStorage.getItem('user')) {
    // TODO localStorage可用于减少请求，从localStorage直接读取用户信息，这个地方后续需要调整，目前只是暂时的简化方案，懒狗叹气
    const loginUser = await GetUserLoginInfo()
    await store.dispatch('submitUser', loginUser)
  }
  // 获取当前路由对登录及授权的要求
  const {
    isLogin,
    isAuth
  } = to.meta
  // 进行判断
  if (localStorage.getItem('user') === null && isLogin) {
    // localStorage中没有用户信息，并且路由要求登录，跳转登录页面
    next('/login')
  } else if (isAuth) {
    // 路由要求授权，通过用户的资源集合判断是否存在对应资源
    let hasAuth = false
    const checkHasAuth = (list, path) => {
      list.forEach(item => {
        if (item.vuePath === path) {
          hasAuth = true
        } else if (item.childList && item.childList.length > 0) {
          checkHasAuth(item.childList, path)
        }
      })
    }
    checkHasAuth(store.getters.user.resourcesList, to.path)
    // 存在对应资源则通过，否则跳转无权限页面
    if (hasAuth) {
      next()
    } else {
      next('/error/401')
    }
  } else {
    // 其他情况通过
    next()
  }
})

export default router
